package com.lh.project.service.impl;


import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lh.project.mapper.VoucherMapper;
import com.lh.project.model.entity.Food;
import com.lh.project.model.entity.SeckillVoucher;
import com.lh.project.model.entity.Voucher;
import com.lh.project.service.FoodService;
import com.lh.project.service.SeckillVoucherService;
import com.lh.project.service.VoucherService;
import io.swagger.models.auth.In;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.lh.project.model.enums.RedisConstants.SECKILL_STOCK_KEY;

/**
*
*/
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher>
implements VoucherService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Resource
    private FoodService foodService;

    @Resource
    private SeckillVoucherService seckillVoucherService;

    @Override
    public List<Voucher> getVoucherByFoodId(long foodId) {
        //判断数据库中是否有id为foodId的food
        Long count = foodService.query().eq("food_id", foodId).count();
        if(count < 1) return null;
        //一个food可能发布多个代金券，所以是List
        List<Voucher> list = query().eq("food_id", foodId+"").eq("status", "1").list();
        if(list==null||list.size()==0){return null;}
        //查出来了代金券
        for(int i = 0;i < list.size();i++){
            //打折
            Voucher voucher = list.get(i);
            String discount =String.valueOf((double)voucher.getPayValue()/voucher.getActualValue()*10);
            list.get(i).setDiscount(discount);
            if(voucher.getType()==0){
                //普通券
                list.get(i).setSeckillVoucher(null);
                continue;
            }
            //秒杀券
            SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucher.getId());
            seckillVoucher.setSeckillPeriod();
            //设置秒杀的时间段
            list.get(i).setSeckillVoucher(seckillVoucher);
        }
        return list;
    }

    @Override
    public void addSeckillVoucher(Voucher voucher) {
        //保持优惠券
        save(voucher);
        //保持秒杀券
        SeckillVoucher seckillVoucher = new SeckillVoucher();

        seckillVoucher.setVoucherId(voucher.getId());
        seckillVoucher.setStock(voucher.getStock());
        seckillVoucher.setBeginTime(voucher.getBeginTime());
        seckillVoucher.setEndTime(voucher.getEndTime());
        seckillVoucherService.save(seckillVoucher);
        //保持优惠券到Redis中去
        stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY+voucher.getId(),voucher.getStock().toString());
    }


}
